import subprocess
import re

class DeviceManager:
    def __init__(self, ffmpeg_path):
        self.ffmpeg_path = ffmpeg_path
        self.devices = {"video": [], "audio": []}
    
    def update_ffmpeg_path(self, ffmpeg_path):
        """更新FFmpeg路径"""
        self.ffmpeg_path = ffmpeg_path
    
    def list_devices(self):
        """列出音视频设备"""
        try:
            # 调用ffmpeg获取设备列表
            cmd = [self.ffmpeg_path, "-list_devices", "true", "-f", "dshow", "-i", "dummy"]
            try:
                # 尝试使用utf-8编码
                result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', shell=True)                
            except UnicodeDecodeError:
                # 如果utf-8失败，尝试使用系统默认编码
                result = subprocess.run(cmd, capture_output=True, shell=True)               
                # 尝试使用不同的编码解码
                try:
                    print(result.stderr.decode('utf-8', errors='replace'))
                except:
                    print("无法解码输出，显示原始字节:")
                    print(result.stderr)
            # 解析输出获取设备信息
            self.devices = {"video": [], "audio": []}
            
            # 使用更直接的解析方式，不再依赖section标记
            if isinstance(result.stderr, bytes):
                output = result.stderr.decode('utf-8', errors='replace')
            else:
                output = result.stderr
            
            # 直接通过正则表达式或关键词匹配来识别设备行
            lines = output.split("\n")
            
            for line in lines:
                line = line.strip()
                # print("处理行:", line)
                
                # 简化设备行判断条件，只要行不为空且包含引号，可能就是设备行
                if line and '"' in line and '[' in line:
                    # print("判断为可能的设备行:", line)
                    try:
                        # 查找设备名称部分（通常在引号中）
                        parts = line.split('"')
                        # print("split后的parts:", parts)
                        if len(parts) > 1:
                            device_name = parts[1]
                            # print("设备名称:", device_name)                            
                            # 直接通过关键词分类设备
                            if any(keyword in device_name.lower() or keyword in line.lower() for keyword in ['video', 'camera', 'webcam', '摄像头', '视频']):
                                if device_name not in self.devices["video"]:
                                    print(f"添加为视频设备: {device_name}")
                                    self.devices["video"].append(device_name)
                            elif any(keyword in device_name.lower() or keyword in line.lower() for keyword in ['audio', 'mic', 'microphone', 'speaker', '麦克风', '扬声器', '音频']):
                                if device_name not in self.devices["audio"]:
                                    print(f"添加为音频设备: {device_name}")
                                    self.devices["audio"].append(device_name)                          
                    except Exception as e:
                        print(f"解析行时出错: {e}")
            
            print(f"解析结果 - 视频设备: {self.devices['video']}")
            print(f"解析结果 - 音频设备: {self.devices['audio']}")
            
            return self.devices
            
        except Exception as e:
            print(f"获取设备列表失败: {str(e)}")
            return {"video": [], "audio": []}
    
    def get_microphone_device(self):
        """尝试获取麦克风设备"""
        # for device in self.devices["audio"]:
        #     if "麦克风" in device or "Microphone" in device:
        #         return device
        return self.devices["audio"][0] if self.devices["audio"] else None
    
    def get_video_devices(self):
        """获取视频设备列表"""
        return self.devices["video"]
    
    def get_audio_devices(self):
        """获取音频设备列表"""
        return self.devices["audio"]